package com.youme.section.main

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.alibaba.android.arouter.facade.annotation.Route
import com.gyf.immersionbar.ImmersionBar
import com.hjq.toast.ToastUtils
import com.hyphenate.EMValueCallBack
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMUserInfo
import com.hyphenate.chat.EMUserInfo.EMUserInfoType
import com.hyphenate.easecallkit.base.EaseCallType
import com.hyphenate.easecallkit.ui.EaseMultipleVideoActivity
import com.hyphenate.easecallkit.ui.EaseVideoCallActivity
import com.hyphenate.easeim.DemoHelper
import com.hyphenate.easeim.MainAdapter
import com.hyphenate.easeim.R
import com.hyphenate.easeim.common.constant.DemoConstant
import com.hyphenate.easeim.common.livedatas.LiveDataBus
import com.hyphenate.easeim.common.permission.PermissionsManager
import com.hyphenate.easeim.common.permission.PermissionsResultAction
import com.hyphenate.easeim.common.utils.PreferenceManager
import com.hyphenate.easeim.common.utils.PushUtils
import com.hyphenate.easeim.section.MainViewModel
import com.hyphenate.easeim.section.chat.ChatPresenter
import com.hyphenate.easeim.section.contact.viewmodels.ContactsViewModel
import com.hyphenate.easeui.model.EaseEvent
import com.hyphenate.util.EMLog
import com.salton123.log.XLog
import com.salton123.ui.base.YoumeBaseActivity
import com.youme.Constants
import com.youme.RouterManager.KEY.Companion.ITEM_KEY
import com.youme.RouterManager.conversationListPage
import com.youme.RouterManager.discoverPage
import com.youme.RouterManager.profilePage
import com.youme.api.Callback
import com.youme.mCurrentUserProfile
import com.youme.model.Profile
import com.youme.viewmodel.YouMeApiViewModel
import kotlinx.android.synthetic.main.activity_youme_main.*

/**
 * @Time:2021/4/6 10:09
 * @Author:wujinsheng
 * @Description:
 */
@Route(path = Constants.Router.YOUME.MAIN)
class MainActivity : YoumeBaseActivity() {

    companion object {
        const val TAG = "MainActivity"
    }

    private val dataList: MutableList<Pair<String, Fragment>> = mutableListOf(
        Pair("conversation", conversationListPage()),
        Pair("discover", discoverPage()),
        Pair("profile", profilePage())

    )
    private val mAdapter by lazy { MainAdapter(supportFragmentManager, dataList) }
    private lateinit var viewModel: MainViewModel
    override fun getLayoutId(): Int = R.layout.activity_youme_main
    private val mImmersionBar by lazy { ImmersionBar.with(this) }
    override fun initSystemFit() {
//        setFitSystemForTheme(false)
        mImmersionBar.statusBarDarkFont(true).init()
    }

    override fun initView(savedInstanceState: Bundle?) {
        initViewModel()
        requestPermissions()
        ChatPresenter.getInstance().init()
        //判断是否为来电推送
        if (PushUtils.isRtcCall) {
            if (EaseCallType.getfrom(PushUtils.type) != EaseCallType.CONFERENCE_CALL) {
                val callActivity = EaseVideoCallActivity()
                val intent =
                    Intent(applicationContext, callActivity.javaClass).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                applicationContext.startActivity(intent)
            } else {
                val callActivity = EaseMultipleVideoActivity()
                val intent = Intent(application.applicationContext, callActivity.javaClass)
                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                applicationContext.startActivity(intent)
            }
            PushUtils.isRtcCall = false
        }
    }

    override fun initViewAndData() {
        viewPager.adapter = mAdapter
        bottomBarLayout.apply {
            setViewPager(viewPager)
            setOnItemSelectedListener { bottomBarItem, previousPosition, currentPosition ->
                XLog.i(TAG, "currentPosition:$currentPosition")
            }
        }
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        val itemKey = intent.getStringExtra(ITEM_KEY)
        val findItem = dataList.find { it.first == itemKey }
        if (findItem != null) {
            bottomBarLayout.currentItem = dataList.indexOf(findItem)
        }
        XLog.i(TAG, "onNewIntent,itemKey:$itemKey")
    }

    private fun initViewModel() {
        viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
        viewModel.homeUnReadObservable()
            .observe(this, Observer<String> { readCount: String? ->
                bottomBarLayout.setUnread(0, readCount?.toInt() ?: 0)
            })

        //加载联系人
        val contactsViewModel = ViewModelProvider(this).get(ContactsViewModel::class.java)
        contactsViewModel.loadContactList(true)
        viewModel.messageChangeObservable().with(DemoConstant.GROUP_CHANGE, EaseEvent::class.java)
            .observe(this, Observer<EaseEvent> { event: EaseEvent? -> checkUnReadMsg(event) })
        viewModel.messageChangeObservable().with(DemoConstant.NOTIFY_CHANGE, EaseEvent::class.java)
            .observe(this, Observer<EaseEvent> { event: EaseEvent? -> checkUnReadMsg(event) })
        viewModel.messageChangeObservable().with(DemoConstant.MESSAGE_CHANGE_CHANGE, EaseEvent::class.java)
            .observe(this, Observer<EaseEvent> { event: EaseEvent? -> checkUnReadMsg(event) })
        viewModel.messageChangeObservable().with(DemoConstant.CONVERSATION_DELETE, EaseEvent::class.java)
            .observe(this, Observer<EaseEvent> { event: EaseEvent? -> checkUnReadMsg(event) })
        viewModel.messageChangeObservable().with(DemoConstant.CONTACT_CHANGE, EaseEvent::class.java)
            .observe(this, Observer<EaseEvent> { event: EaseEvent? -> checkUnReadMsg(event) })
        viewModel.messageChangeObservable().with(DemoConstant.CONVERSATION_READ, EaseEvent::class.java)
            .observe(this, Observer<EaseEvent> { event: EaseEvent? -> checkUnReadMsg(event) })
        val mViewModel: YouMeApiViewModel = ViewModelProvider(this).get(YouMeApiViewModel::class.java)

        mViewModel.profile(object : Callback<Profile> {
            override fun onSuccess(value: Profile) {
//                CIMPushManager.connect(mContext,"39.101.132.116",23456)
//                CIMPushManager.bindAccount(mContext,"{\"type\":\"1\",\"deskId\":\"3860815f-432c-4c11-9466-be9d3aad9524\",\"userName\":\"admin\"}")
//                ToastUtils.show(value)
                mCurrentUserProfile = value
                DemoHelper.getInstance().userProfileManager.updateCurrentUserNickName(value.nickName)
                DemoHelper.getInstance().userProfileManager.uploadUserAvatar(value.avatar.toByteArray())
                DemoHelper.getInstance().userProfileManager.asyncGetCurrentUserInfo()
            }

            override fun onFailed(errorCode: Int, errorMessage: String, throwable: Throwable?) {
                ToastUtils.show("获取资料失败,$errorCode,$errorMessage,$throwable")
                Log.i("errorMessage", "errorMessage : " + errorMessage + "throwable" + throwable)
            }
        })
    }

    private fun checkUnReadMsg(event: EaseEvent?) {
        if (event == null) {
            return
        }
        viewModel.checkUnreadMsg()
    }

    private fun requestPermissions() {
        PermissionsManager.getInstance()
            .requestAllManifestPermissionsIfNecessary(this,
                object : PermissionsResultAction() {
                    override fun onGranted() {}
                    override fun onDenied(permission: String) {}
                })
    }

    private fun fetchSelfInfo() {
        val userId = arrayOfNulls<String>(1)
        userId[0] = EMClient.getInstance().currentUser
        val userInfoTypes = arrayOfNulls<EMUserInfoType>(2)
        userInfoTypes[0] = EMUserInfoType.NICKNAME
        userInfoTypes[1] = EMUserInfoType.AVATAR_URL
        EMClient.getInstance().userInfoManager().fetchUserInfoByAttribute(userId, userInfoTypes,
            object : EMValueCallBack<Map<String?, EMUserInfo?>> {
                override fun onSuccess(userInfos: Map<String?, EMUserInfo?>) {
                    runOnUiThread {
                        val userInfo = userInfos[EMClient.getInstance().currentUser]
                        //昵称
                        if (userInfo != null && userInfo.nickName != null && userInfo.nickName.isNotEmpty()) {
                            val event =
                                EaseEvent.create(DemoConstant.NICK_NAME_CHANGE, EaseEvent.TYPE.CONTACT)
                            event.message = userInfo.nickName
                            LiveDataBus.get().with(DemoConstant.NICK_NAME_CHANGE).postValue(event)
                            PreferenceManager.getInstance().currentUserNick = userInfo.nickName
                        }
                        //头像
                        if (userInfo != null && userInfo.avatarUrl != null && userInfo.avatarUrl.isNotEmpty()) {
                            val event =
                                EaseEvent.create(DemoConstant.AVATAR_CHANGE, EaseEvent.TYPE.CONTACT)
                            event.message = userInfo.avatarUrl
                            LiveDataBus.get().with(DemoConstant.AVATAR_CHANGE).postValue(event)
                            PreferenceManager.getInstance().currentUserAvatar = userInfo.avatarUrl
                        }
                    }
                }

                override fun onError(error: Int, errorMsg: String) {
                    EMLog.e("MainActivity", "fetchUserInfoByIds error:$error errorMsg:$errorMsg")
                }
            })
    }
}